package study.edumanagesystemspringboot.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import study.edumanagesystemspringboot.config.ResultMap;
import study.edumanagesystemspringboot.entity.Admin;
import study.edumanagesystemspringboot.service.IAdminService;

import java.util.HashMap;
import java.util.Map;

/**
 * 管理员登录
 *
 * @author zouran
 * createDate：2023/12/30  14:58
 */
@RestController
@RequestMapping("/admin")
public class AdminController {
    private final IAdminService iAdminService;
    private final ResultMap<Object> resultMap;

    public AdminController(IAdminService iAdminService, ResultMap<Object> resultMap) {
        this.iAdminService = iAdminService;
        this.resultMap = resultMap;
    }

    /**
     * 登录
     *
     * @param accountNumber 账号
     * @param password      密码
     * @return token, identify-route
     */
    @RequestMapping("/login")
    public ResultMap<Object> login(@Param("accountNumber") String accountNumber, @Param("password") String password) {
        Admin admin = iAdminService.checkLogIn(accountNumber, password);
        if (admin == null)
            return resultMap.successWithMessage("账号或密码错误!");
        else {
            // 第1步，先登录上
            StpUtil.login(accountNumber);
            // 第2步，获取 Token  相关参数
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            Map<String, String> map = new HashMap<>();
            map.put("token", tokenInfo.tokenValue);
            map.put("route", admin.getIdentify());
            map.put("accountName", admin.getAccountName());
            map.put("headSculpture", admin.getHeadSculpture());
            return resultMap.success(map);
        }
    }

    /**
     * 注销
     *
     * @param accountNumber 账号
     * @return code:200
     */
    @RequestMapping("/logout")
    public ResultMap<Object> logout(@Param("accountNumber") String accountNumber) {
        StpUtil.logout(accountNumber);
        return resultMap.success("");
    }

    /**
     * 检验登录
     *
     * @return 检验登录code
     */
    @RequestMapping("/checkLogin")
    public ResultMap<Object> checkLogin() {
        StpUtil.checkLogin();
        return resultMap.success("");
    }
}
